package com.foundersoftware.template.excel.imple;

import java.io.FileInputStream;
import java.util.List;

import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.foundersoftware.exception.ParserExcelException;
import com.foundersoftware.template.excel.IParserTemplate;

/**
 * The interface contain find matching excel template.
 * @author	JiDong
 * @create	December 2.2009
 * 
 *
 */
public class ParserTemplateImpl implements IParserTemplate{
	
	private static final Log 	log = LogFactory.getLog(ParserTemplateImpl.class);
	private HSSFWorkbook 		workbook;
	
	public HSSFWorkbook getWorkbook() {
		return workbook;
	}

	public void setWorkbook(HSSFWorkbook workbook) {
		this.workbook = workbook;
	}

	public void findTemplateByTemplateName(String templateName,ServletContext servletContext) {
		if (!"".equals(templateName) && null != templateName) {
			new ParserExcelException("Template name shoult not null.");
		}
		
		List<String> templateNames = (List<String>) servletContext.getAttribute("templateNames");
		String path = servletContext.getRealPath("");
		for (String name : templateNames) {
			if (templateName.equals(name)) {
				path+="/template/"+name;
				parserTemplate(path);
			}
		}
	}
	
	private void parserTemplate(String path) {
		if ("".equals(path) && null == path) {
			new ParserExcelException("Not sepcify template name.");
		}
		
		try {
			workbook = new HSSFWorkbook(new FileInputStream(path));			
		} catch (Exception e) {
			log.error("parser excel appear exception :"+e.getMessage()+" in class :"+e.getClass()+" stack :"+e.getStackTrace());
			new ParserExcelException(e);
		} 
	}
}
